from copy import deepcopy


def flat_dict(input_dict: dict) -> dict:
    """
    扁平化字典，至多只能扁平两层，扁平后用下划线连接
    input_dict = {'ipmi': {'user': 'admin', 'password': '12345'}}
    output_dict = {'ipmi_user': 'admin', 'ipmi_password': '12345'}
    :param input_dict: 需要扁平的字典
    :return: output_dict
    """
    if not isinstance(input_dict, dict):
        raise Exception('input param must be dict')
    output_dict = deepcopy(input_dict)
    for k, v in input_dict.items():
        if isinstance(v, dict):
            for _k, _v in v.items():
                if isinstance(_v, dict):
                    raise Exception('input param only have two layers at most')
                else:
                    output_dict['{}_{}'.format(k, _k)] = _v
            del output_dict[k]
    return output_dict


def calc_string_in_list(str1, list1) -> int:
    return len([i for i in list1 if str1 in i])


def merge_dict(input_dict: dict) -> dict:
    """
    合并带下划线的字典，至多只能扁平两层，扁平后用下划线连接
    input_dict = {'ipmi_user': 'admin', 'ipmi_password': '12345'}
    output_dict = {'ipmi': {'user': 'admin', 'password': '12345'}}
    :param input_dict: 需要合并的字典
    :return: output_dict
    """
    if not isinstance(input_dict, dict):
        raise Exception('input param must be dict')
    output_dict = {}
    _keys = [i for i in input_dict.keys() if '_' in i and i[0] != '_']
    # _split=包含下划线的字典key
    _split = sum([i.split('_') for i in _keys], [])
    # _flag=需要合并的字典标志
    _flag = set([k for k in _split if calc_string_in_list(k + '_', _keys) >= 2])
    for k, v in input_dict.items():
        start = k.split('_')[0]
        if start + '_' in k and start in _flag and len(k.split('_')) >= 2:
            output_dict.setdefault(start, {})
            end = k.split('_')[1]
            output_dict[start][end] = v
        else:
            output_dict[k] = v
    return output_dict


def filter_dict_start_witch_(input_dict):
    if not isinstance(input_dict, dict):
        raise Exception('input param must be dict')
    keys = [i for i in input_dict.keys() if i[0] == '_']
    for key in keys:
        input_dict.pop(key)
    return input_dict


if __name__ == '__main__':
    input_dict = {'ipmi': {'user': 'admin', 'password': '12345'}}
    output_dict = {'ipmi_user': 'admin', 'ipmi_password': '12345'}
    print('flat_dict', input_dict, '->', flat_dict(input_dict))
    print('merge_dict', output_dict, '->', merge_dict(output_dict))
